package com.allenkerr.mail.service.impl;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import com.allenkerr.mail.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

/**
 * Created by 小柯 on 17/7/20.
 */
@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    private static final Logger LOGGER = LoggerFactory.getLogger(MailServiceImpl.class);

    @Override
    public void sendSimpleMail(SimpleMailMessage message) {

        if (message == null) return;

        message.setFrom(from);

        //send mail
        try {
            mailSender.send(message);
            LOGGER.info("succeed in sending mail.");
        } catch (MailException e) {
            LOGGER.error("send mail error.", e);
        }
    }

    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        //create mail
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);

        //send mail
        sendSimpleMail(message);
    }

    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        //create mail
        MimeMessage message = mailSender.createMimeMessage();

        //setup mail
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);//true --> multipart message
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
        } catch (MessagingException e) {
            LOGGER.error("setup mail error.", e);
        }

        //send mail
        try {
            mailSender.send(message);
            LOGGER.info("succeed in sending mail.");
        } catch (MailException e) {
            LOGGER.error("send mail error.", e);
        }
    }

    @Override
    public void sendAttachmentsMail(String to, String subject, String content, File... files) {
        //create mail
        MimeMessage message = mailSender.createMimeMessage();

        //setup mail
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            //添加附件
            if (files != null) {
                for (int i = 0; i < files.length; i++) {
                    String fileName = files[i].getName();
                    helper.addAttachment(fileName, files[i]);
                }
            }
        } catch (MessagingException e) {
            LOGGER.error("setup mail error.", e);
        }

        //send mail
        try {
            mailSender.send(message);
            LOGGER.info("succeed in sending mail.");
        } catch (MailException e) {
            LOGGER.error("send mail error.", e);
        }
    }

    @Override
    public void sendAttachmentsMail(String to, String subject, String content, String... filePaths) {
        List<File> fileList = new LinkedList<>();
        if (filePaths != null) {
            for (int i = 0; i < filePaths.length; i++) {
                if (filePaths[i] != null) {
                    fileList.add(new File(filePaths[i]));
                }
            }
        }
        File[] files = fileList.toArray(new File[fileList.size()]);
        this.sendAttachmentsMail(to, subject, content, files);
    }

    @Override
    public void sendAttachmentsMail(String to, String subject, String content, InputStreamSource... streamSources) {
        //create mail
        MimeMessage message = mailSender.createMimeMessage();

        //setup mail
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            //添加附件
            if (streamSources != null) {
                for (int i = 0; i < streamSources.length; i++) {
                    helper.addAttachment("attachment_" + (i + 1) + ".jpg", streamSources[i]);
                }
            }
        } catch (MessagingException e) {
            LOGGER.error("setup mail error.", e);
        }

        //send mail
        try {
            mailSender.send(message);
            LOGGER.info("succeed in sending mail.");
        } catch (MailException e) {
            LOGGER.error("send mail error.", e);
        }
    }

    @Override
    public void sendAttachmentsMail(String to, String subject, String content, URL... urls) {
        List<InputStreamSource> streamSourceList = new LinkedList<>();
        try {
            if (urls != null) {
                for (int i = 0; i < urls.length; i++) {

                    if (urls[i] != null) {
                        //获取输入流
                        InputStream inputStream = urls[i].openStream();
                        //转 byte[]
                        byte[] bytes = FileCopyUtils.copyToByteArray(inputStream);
                        //转 InputStreamSource
                        InputStreamSource streamSource = new ByteArrayResource(bytes);

                        streamSourceList.add(streamSource);
                    }
                }
            }
        } catch (IOException e) {
            LOGGER.error("io exception.", e);
        }

        InputStreamSource[] streamSources = streamSourceList
                .toArray(new InputStreamSource[streamSourceList.size()]);

        this.sendAttachmentsMail(to, subject, content, streamSources);
    }

}
